package com.ganxiang.ximenhong.base;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Environment;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.ganxiang.ximenhong.config.ImageConfig;

import java.io.File;
import java.util.LinkedList;

public class XiMenHongApplication extends Application{
	
	private static XiMenHongApplication mXiMenGongApplication;
	private  LinkedList<Activity> mActivitys;
    private static final String APPLICATION_DIR = "xiMenHong";
	
	@Override
	public void onCreate() {
		super.onCreate();
		Fresco.initialize(this);
		ImageConfig.initImageLoader(this);
	}
	
	public static XiMenHongApplication getIntanst() {
		if (mXiMenGongApplication == null) {
			synchronized (XiMenHongApplication.class) {
				mXiMenGongApplication = new XiMenHongApplication();
			}
		}
		return mXiMenGongApplication;
	}
	
	public void addActivity(Activity activity) {
		if (mActivitys == null) {
			synchronized (LinkedList.class) {
				mActivitys = new LinkedList<Activity>();
			}
		}
		if (mActivitys != null && mActivitys.size() > 0) {
			if (!mActivitys.contains(activity)) {
				mActivitys.add(activity);
			}
		} else {
			mActivitys.add(activity);
		}
	}

	public void removeActivity(Activity activity) {
		if (mActivitys != null && mActivitys.size() > 0) {
			if (mActivitys.contains(activity)) {
				mActivitys.remove(activity);
			}
		}
	}

	
	
	public void finishAllActivity() {
		if (mActivitys != null && mActivitys.size() > 0) {
			for (Activity activity : mActivitys) {
				activity.finish();
			}
		}
	}

	public void finishAllActivityExceptMainActivity() {
		if (mActivitys != null && mActivitys.size() > 0) {
			for(int i = mActivitys.size() - 1; i >= 0; i = mActivitys.size() - 1){
				System.out.println("====>"+mActivitys.get(i).getClass().getName());
				mActivitys.get(i).finish();
				mActivitys.remove(i);	
			}
		}
	}
	
	/**
	 * 
	 * 获得app下所以缓存文件的根目录
	 * @param context
	 * @return
	 */
	public File getApplicaionCacheDir(Context context){
		File sdDir = null; 
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            sdDir = Environment.getExternalStorageDirectory();
        }
        else{
        	sdDir = context.getCacheDir();
        }  
		File cacheDir = new File(sdDir, APPLICATION_DIR);
		if(!cacheDir.exists()){
			cacheDir.mkdirs();
		}	
		return cacheDir;
	}
	
	/**
	 * 
	 * 获得app缓存文件根目录下某个指定的文件夹
	 * @param context
	 * @param cacheDir
	 * @return
	 */
	public File makeFileCacheDir(Context context,String cacheDir){
		File applicationRootCacheDir = getApplicaionCacheDir(context);
		File childCacheDir = new File(applicationRootCacheDir, cacheDir);
		if(!childCacheDir.exists()){
			childCacheDir.mkdirs();
		}
		return childCacheDir;
	}
}
